package com.itlaobing.demo.servlet;

import com.itlaobing.demo.model.UserinfoModel;
import com.itlaobing.demo.util.DBHelper;
import com.itlaobing.demo.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Classname UserServlet
 * @Description TODO()
 * @Date 2020/11/12 0012 10:11
 * @Author by Administrator
 * @Version v1.0
 */
@WebServlet("/userlist")
public class UserServlet extends HttpServlet {

    private DBHelper db = new DBHelper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageSize = req.getParameter("size"); // 页大小，每页有多少数据
        String pageNum = req.getParameter("num"); // 页码

        // 默认值
        Integer size = 5;
        Integer num = 1;
        if (!(pageSize == null || "".equals(pageSize))) {
            size = Integer.parseInt(pageSize);
        }
        if (!(pageNum == null || "".equals(pageNum))) {
            num = Integer.parseInt(pageNum);
        }
        // 查询数据库中用户列表
        String sql = "select  `id`, `username`, `name`, `imgUrl` , `age`, `createDate`, `gender`, `hobby`, `province`, `birthday` from userinfo order by createDate desc limit ?, ?";
        List<UserinfoModel> userinfoModels = db.executeQueryList(sql, UserinfoModel.class, (num - 1) * size, size);
        sql = "select count(*) from userinfo";
        ResultSet rs = db.executeQuery(sql);
        int count = 0;
        try {
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        // request域set属性 key = list ， value=用户信息列表
        req.setAttribute("list", userinfoModels);
        req.setAttribute("page", new PageUtil(num, size, count));
        // 请求转发到 用户列表页面
        req.getRequestDispatcher("WEB-INF/pages/sys/userlist.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
